package com.mars.sso.client.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSON;
import com.mars.base.common.contants.SSOConfig;
import com.mars.base.common.utils.CookieUtils;

public class SSOFilter implements Filter {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	// 不需要拦截的URI模式，以正则表达式表示
	private String excludes;
	// 服务器公网访问地址
	private String serverBaseUrl;
	// 业务系统与SSO系统间通信的内网地址
	private String serverInnerAddress;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.excludes = filterConfig.getInitParameter("excludes");
		this.serverBaseUrl = filterConfig.getInitParameter("serverBaseUrl");
		this.serverInnerAddress = filterConfig.getInitParameter("serverInnerAddress");

		if (serverBaseUrl == null || serverInnerAddress == null) {
			throw new ServletException("SSOFilter配置错误，必须配置serverBaseUrl和serverInnerAddress");
		}

		TokenManager.serverInnerAddress = serverInnerAddress;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		
		//logger.debug("SSOFilter，当前请求URL:{}", request.getRequestURL());
		
		// 如果不需要拦截的请，直接通过
		if (requestIsExclude(request)) {
			chain.doFilter(request, response);
			return;
		}
		
		// 进行登录状态验证
		String token = CookieUtils.getCookieValue(request, SSOConfig.SSO_TOKEN);
		if (null != token && !StringUtils.isEmpty(token)) {
			SSOUser user = null;

			try {
				user = TokenManager.validate(token);
			} catch (Exception e) {
				PrintWriter out = response.getWriter();
				Map<String, Object> map = new HashMap<String, Object>();
				response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                map.put("status", response.getStatus());
                map.put("message", e.getMessage());
                out.print(JSON.toJSONString(map));
                return ;
			}
			
			if (user != null) {
				holdUser(user, request); // 将user存放，供业务系统使用
				CookieUtils.setCookie(request, response, SSOConfig.SSO_TOKEN, token, SSOConfig.TIMEOUT);
				chain.doFilter(request, response); // 请求继续向下执行
			} else {
				CookieUtils.deleteCookie(request, response, SSOConfig.SSO_TOKEN);	//删除无效的Token
				response.setStatus(412);	//返回登录超时状态码
				return ;
			}

		} else {
			// 返回登录超时状态码
			response.setStatus(412);
			return ;
		}

	}

	@Override
	public void destroy() {

	}

	// 将User存入threadLocal和request中，供业务系统使用
	private void holdUser(SSOUser user, ServletRequest request) {
		UserHolder.setUser(user, request);
	}

	/**
	 * 判断请求是否不需要拦截<br>
	 * 如不需要拦截的请求，在Filter中配置如下正则表达式 ^/((about$)|(contact$)|(notmember/.+))
	 * 
	 * @param request
	 * @return
	 */
	private boolean requestIsExclude(HttpServletRequest request) {
		// 没有设定excludes是，所有经过filter的请求都需要被处理
		if (StringUtils.isEmpty(excludes)) {
			return false;
		}

		// 获取去除context path后的请求路径
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		uri = uri.substring(contextPath.length());

		Pattern p = Pattern.compile(excludes);
		Matcher m = p.matcher(uri);
		// 正则表达式匹配URI被排除，不需要拦截
		boolean isExcluded = m.find();
		if (isExcluded) {
			logger.debug("request path: {} is excluded!", uri);
		}

		return isExcluded;
	}

}
